<?php

namespace common\models;

use Yii;
use yii\db\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "package".
 *
 * @property string $id
 * @property string $code
 * @property string $title
 * @property integer $category
 * @property integer $type
 * @property string $access
 * @property string $access_users
 * @property string $creditor
 * @property integer $province
 * @property integer $city
 * @property string $principal
 * @property integer $principal_range
 * @property string $interest
 * @property string $hushu
 * @property string $broke_principal
 * @property string $detail
 * @property integer $state
 * @property string $origin
 * @property string $industry
 * @property string $owner
 * @property string $limit_collection
 * @property integer $teamwork
 * @property string $created_at
 * @property string $updated_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 * @property integer $is_finished
 */
class Package extends \yii\db\ActiveRecord
{
    //资产包类别
    const CATEGORY_A = 1;
    const CATEGORY_B = 2;
    const CATEGORY_C = 3;
    const CATEGORY_D = 4;

    //资产包状态
    const STATE_BASE = 1;
    const STATE_INITIATIN = 2;
    const STATE_APPROVAL = 3;
    const STATE_EVALUATION = 4;
    const STATE_TRANSFER = 5;
    const STATE_FOLLOW = 6;

    //origin
    const ORIGIN_INTERIOR = 1;
    const ORIGIN_EXTERNAL = 2;

    //teamwork
    const TEAMWORK_TRUE = 1;
    const TEAMWORK_FALSE = 0;

    private $category_array_title = array(
        self::CATEGORY_A => 'A自有资产包',
        self::CATEGORY_B => 'B管理资产包',
        self::CATEGORY_C => 'C共投共管资产包',
        self::CATEGORY_D => 'D立项新包'
    );

    private $state_array_title = array(
        self::STATE_BASE => '无',
        self::STATE_INITIATIN => '启动尽调',
        self::STATE_APPROVAL => '已立项',
        self::STATE_EVALUATION => '已评估',
        self::STATE_TRANSFER => '已受让',
        self::STATE_FOLLOW => '待跟进'
    );

    private $origin_array_title = array(
        self::ORIGIN_INTERIOR => '内部上传',
        self::ORIGIN_EXTERNAL => '自动入库'
    );

    private $teamwork_array_title = array(
        self::TEAMWORK_TRUE => '是',
        self::TEAMWORK_FALSE => '否'
    );

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'type', 'owner'], 'required'],
            //[['title', 'type', 'access_users', 'owner'], 'required'],
            //[['code', 'title', 'type', 'access_users', 'creditor', 'province', 'city', 'currency', 'principal', 'principal_range', 'interest', 'hushu', 'detail', 'state','origin', 'owner', 'attachment', 'created_at', 'updated_at'], 'required'],
            [['category', 'type', 'province',
                'principal_range', 'state', 'owner', 'teamwork', 'lock_user', 'is_finished', 'hushu',], 'integer'],
            //[['principal', 'interest'], 'double'],
            [['detail', 'industry','limit_collection', 'origin',/*, 'attachment'*/], 'string'],
            [['created_at', 'updated_at'], 'safe'],
            [['code', 'title', 'city', 'access', 'access_users', 'creditor', 'principal', 'interest', 'broke_principal', 'lock_timestamp'], 'string', 'max' => 255],
            //[['title'], 'unique'],
            ['title', 'validateTitle'],
            ['principal', 'validatePrincipal'],
            ['interest', 'validateInterest'],
            ['hushu', 'validateHushu'],
        ];
    }

    //验证资产包唯一性
    public function validateTitle()
    {
        if ($this->title == '') {
            $this->addError('title', '资产包名称不能为空。');
        } else {
            if ($this->id) {
                $list = $this::find()->where(['title'=>$this->title,'is_finished'=>1])->andWhere(['<>', 'id', $this->id])->all();
                if (!empty($list)) {
                    $this->addError('title', '资产包名称的值"'. $this->title .'"已经被占用了');
                }
            } else {
                $model = $this::find()->where(['title'=>$this->title,'is_finished'=>1])->one();
                if ($model !== null) {
                    $this->addError('title', '资产包名称的值"'. $this->title .'"已经被占用了');
                }
            }
        }
    }


    //验证本金
    public function validatePrincipal()
    {
        if (!is_numeric($this->principal) && $this->principal !='' ) {
            $number = self::set_number_format($this->principal);
            if ($this->principal != $number) {
                $this->addError('principal', '本金格式不正确。');
            }
        }
    }

    //验证利息
    public function validateInterest()
    {
        if (!is_numeric($this->interest) && $this->interest !='' ) {
            $number = self::set_number_format($this->interest);
            if ($this->interest != $number) {
                $this->addError('principal', '利息格式不正确。');
            }
        }
    }

    //验证户数
    public function validateHushu()
    {
        if (($this->hushu != null) && !is_integer($this->hushu)) {
            $this->addError('hushu', '户数为整数。');
        }
    }

    /**
     * @param $number string
     * @return string
     */
    public static function set_number_format($number)
    {
        $format_number = str_replace(',','',$number);
        if (is_numeric($format_number)) {
            $strlen = strrpos($format_number,'.');
            if ($strlen) {
                $str1 =  substr($format_number, $strlen);
                $str2 = number_format(substr($format_number,0,$strlen));
                $str = $str2 . $str1;
            }
        } else {
            $str = $format_number . 'error';
        }
        return $str;
    }

    /*关联package_initiation 表 (ly)*/
    public function getInitiation()
    {
        return $this->hasOne(PackageInitiation::className(), ['package_id' => 'id']);
    }

    /*关联Project表 (ly)*/
    public function getProject()
    {
        return $this->hasMany(Project::className(), ['package_id' => 'id']);
    }

    /*关联用户表（ly）*/
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'lock_user']);
    }

    /*关联省市*/
    public function getProvinceName()
    {
        return $this->hasOne(Country::className(), ['id' => 'province'])->asArray();
    }

    /*关联城市表*/
    public function getCityName()
    {
        return $this->hasOne(Country::className(), ['id' => 'city'])->asArray();
    }

    /*关联流转记录 history*/
    public function getHistory()
    {
        return $this->hasMany(PackageTransferHistory::className(), ['package_id' => 'id']);
    }

    //关联package_initiation_income
    public function getIncome()
    {
        return $this->hasMany(PackageInitiationIncome::className(), ['package_id' => 'id']);
    }

    // 关联 package_initiation_plan
    public function getPlan()
    {
        return $this->hasMany(\common\models\PackageInitiationPlan::className(), ['package_id' => 'id']);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'code' => '编号',
            'title' => '资产包名称',
            'category' => '资产包类别',
            'type' => '资产类型',
            'access' => 'access',
            'access_users' => '部分访问的人的ID',
            'creditor' => '债权人',
            'province' => '省份',
            'city' => '城市',
            //'currency' => '币种',
            'principal' => '本金（元）',
            'principal_range' => '本金额度',
            'interest' => '利息（元）',
            'hushu' => '户数',
            'broke_principal' => '破产本金',
            'detail' => '详细说明',
            'state' => '状态',
            'origin' => '渠道来源',
            'industry' => '行业',
            'owner' => '上传人',
            'limit_collection' => '未诉债权时效及催收方式',
            //'attachment' => '清单',
            'teamwork' => '是否发起协同',
            'created_at' => '上传时间',
            'updated_at' => '更新时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
            'is_finished' => '是否完成',
        ];
    }

    /**
     * 资产包类别
     *
     * @return array
     */
    public function getCategoryArrayTitle()
    {
        return $this->category_array_title;
    }

    /**
     * 资产包类型
     *
     * @return mixed
     */
    public function getTypeArrayTitle()
    {
        //return unserialize(PACKAGE_TYPE);(ly改)
        return Yii::$app->params['package_type'];
    }

    /**
     * 本金额度
     *
     * @return mixed
     */
    public function getPrincipalRangeTitle()
    {
        return Yii::$app->params['principalRange'];
    }

    /**
     * 状态
     *
     * @return array
     */
    public function getStateTitle()
    {
        return $this->state_array_title;
    }

    /**
     * 渠道来源
     *
     * @return array
     */
    public function getOriginTitle()
    {
        return $this->origin_array_title;
    }

    /**
     * 是否发起协同
     *
     * @return array
     */
    public function getTeamworkTitle()
    {
        return $this->teamwork_array_title;
    }

    /**
     * 重名则删除之前未完成的上传流程
     * @param $title  资产包名称
     * @throws Exception
     */
    public function validatorTitle($title)
    {
        $packageInfo = $this::find()->where(['title' => $title, 'is_finished' => 0])->one();
        if (!empty($packageInfo)) {
            $transaction = Yii::$app->db->beginTransaction();
            try{
                //删除资产包
                $re = $packageInfo->delete($packageInfo->id);
                if (!$re) {
                    throw new Exception('删除未完成的同名资产包失败');
                }

                //删除资产包日志
                $packageLogList = PackageLog::find()->where(['package_id' => $packageInfo->id])->all();
                if (!empty($packageLogList)) {
                    $packageLog = new PackageLog();
                    $re = $packageLog->deleteAll(['package_id' => $packageInfo->id]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包日志失败');
                    }
                }

                //删除资产包修改日志
                $packageUpdateLogList = PackageUpdateLog::find()->where(['package_id' => $packageInfo->id])->all();
                if (!empty($packageUpdateLogList)) {
                    $packageUpdateLog = new PackageUpdateLog();
                    $re = $packageUpdateLog->deleteAll(['package_id' => $packageInfo->id]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包日志失败');
                    }
                }

                //删除项目
                $projectList = Project::find()->where(['package_id' => $packageInfo->id, 'is_finished' => 0])->all();
                if (!empty($projectList)) {
                    $project_id_array = ArrayHelper::getColumn($projectList, 'id');
                    $data = array();
                    foreach ($project_id_array as $value) {
                        $data[] = (int)$value;
                    }

                    //删除项目日志
                    $project_log = new ProjectLog();
                    $project_log_list = ProjectLog::find()->where(['in', 'id', $data])->all();
                    if (!empty($project_log_list)) {
                        $resLog = $project_log->deleteAll(['in', 'id', $data]);
                        if (!$resLog) {
                            throw new Exception('删除未完成的同名资产包下的项目日志失败');
                        }
                    }

                    //删除项目
                    $project = new Project();
                    $re = $project->deleteAll(['package_id' => $packageInfo->id, 'is_finished' => 0]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包下的项目失败');
                    }
                }

                //资产包转让
                $packageTransferList = PackageTransfer::find()->where(['package_id' => $packageInfo->id])->all();
                if (!empty($packageTransferList)) {
                    $packageTransfer = new PackageTransfer();
                    $re = $packageTransfer->deleteAll(['package_id' => $packageInfo->id]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包流转表失败');
                    }
                }

                //资产包流转记录初始表
                $packageTransferHistoryInitList = PackageTransferHistoryInit::find()->where(['package_id' => $packageInfo->id])->all();
                if (!empty($packageTransferHistoryInitList)) {
                    $packageTransferHistoryInit = new PackageTransferHistoryInit();
                    $re = $packageTransferHistoryInit->deleteAll(['package_id' => $packageInfo->id]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包转让记录初始表失败');
                    }
                }

                //资产包转让记录表
                $packageTransferHistoryList = PackageTransferHistory::find()->where(['package_id' => $packageInfo->id])->all();
                if (!empty($packageTransferHistoryList)) {
                    $packageTransferHistory = new PackageTransferHistory();
                    $re = $packageTransferHistory->deleteAll(['package_id' => $packageInfo->id]);
                    if (!$re) {
                        throw new Exception('删除未完成的同名资产包转让记录表失败');
                    }
                }
                $transaction->commit();
                return array('state'=>true, 'msg'=>'删除成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                return array('state'=>false, 'msg'=>'删除失败');
            } catch (\Throwable $e) {
                $transaction->rollBack();
                return array('state'=>false, 'msg'=>'删除失败');
            }
        }
        return array('state'=>true, 'msg'=>'');
    }

    /**
     * 新增资产包
     *
     * @param $model  Package对象
     * @param $userId 用户
     */
    public function addPackage($model, $userId)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $re = $model->save();
            if (!$re) {
                throw new Exception('添加资产包基本信息失败');
            }

            //$users = explode(',', $this->access_users);
            //if (!empty($users) && is_array($users)) {
            //    foreach ($users as $k => $v) {
            //        $userPackage = new UserPackage();
            //        $userPackage->package_id = $this->id;
            //        $userPackage->created_at = time();
            //        $userPackage->updated_at = 0;
            //        $userPackage->user_id = (int)$v;
            //        $re = $userPackage->save();
            //        if (!$re) {
            //            throw new Exception('资产包关联部门失败');
            //        }
            //    }
            //}

            $packageLog = new PackageLog();
            $packageLog->package_id = $model->id;
            $packageLog->created_at = date('Y-m-d H:i:s');
            $packageLog->user_id = $userId;
            $packageLog->log = "新增资产包【{$model->title}】";
            $re = $packageLog->save();
            if (!$re) {
                throw new Exception('资产包日志保存失败');
            }

            $transaction->commit();
            return array('state' => true, 'msg' => '保存成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return array('state' => false, 'msg' => $e->getMessage());
        } catch (\Throwable $e) {
            $transaction->rollBack();
            return array('state' => false, 'msg' => $e->getMessage());
        }
    }

    /**
     * 编辑资产包
     *
     * @param $id
     * @param $data  更新数据
     * @param $userId 用户id
     */
    public function editPackage($id, $data, $userId)
    {
        if (!empty($data) && is_array($data)) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $model = $this::findOne($id);
                $users = new UserModel();
                $realname = $users->getRealname($userId);
                $userList = $users->getDepartmentUsersList();
                //省市
                $country_title = Country::getTitleList();
                //模型属性
                $attributeLabels = $model->attributeLabels();
                //整型属性
                $intAttributeLabels = ['category', 'type', 'access', 'access_users', 'province', 'city', 'principal_range', 'state', 'origin', 'owner', 'teamwork', 'lock_user'];

                $log = '';
                foreach ($data as $key => $value) {
                    $model->$key = $value;
                    if (in_array($key, $intAttributeLabels)) {
                        switch ($key) {
                            case 'category':
                                $title = $model->getCategoryArrayTitle();
                                $value = $title[$value];
                                break;
                            case 'type':
                                $title = $model->getTypeArrayTitle();
                                $value = $title[$value];
                                break;
                            case 'access':
                                if (is_numeric($value)) {
                                    $title = Yii::$app->params['access'];
                                    $value = $title[$value];
                                }
                                break;
                            case 'access_users':
                                $arr = explode(',', trim($value, ','));
                                $str = '';
                                foreach ($arr as $v) {
                                    $str .= $userList[(int)$v]['realname'] .'，';
                                }
                                $value = mb_substr($str, 0, -1, 'utf-8');
                                break;
                            case 'province':
                                $value = $country_title[$value];
                                break;
                            case 'city':
                                if ($value != '') {
                                    $arr = explode(',', $value);
                                    $array = array();
                                    foreach ($arr as $k=>$v) {
                                        if ($v > 0){
                                            $array[] = $country_title[(int)$v];
                                        }
                                    }
                                    $value = join('、', $array);
                                } else {
                                    $value = '';
                                }
                                break;
                            case 'principal_range':
                                $title = $model->getPrincipalRangeTitle();
                                $value = $title[$value];
                                break;
                            case 'state':
                                $title = $model->getStateTitle();
                                $value = $title[$value];
                                break;
                            case 'origin':
                                $title = $model->getOriginTitle();
                                $value = $title[$value];
                                break;
                            case 'teamwork':
                                $title = $model->getTeamworkTitle();
                                $value = $title[$value];
                                break;
                            case 'owner':
                                $value = $realname;
                                break;
                            case 'lock_user':
                                $value = $realname;
                                break;
                            default:
                        }
                    }
                    $log .= "{$attributeLabels[$key]}：{$value}\n";
                }

                $res = $model->save();
                if (!$res) {
                    throw new Exception('资产包基本信息更新失败');
                }

                $current_date = date('Y-m-d H:i:s');

                $packageUpdateLog = new PackageUpdateLog();
                $ModuleArrayTitle = $packageUpdateLog->getModuleArrayTitle();
                $packageUpdateLog->package_id = $model->id;
                $packageUpdateLog->module = $ModuleArrayTitle[$packageUpdateLog::MODULE_BASE];
                $packageUpdateLog->created_at = $current_date;
                $packageUpdateLog->user_id = $userId;
                $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
                $re = $packageUpdateLog->save();
                if (!$re) {
                    throw new Exception('资产包更新日志保存失败');
                }

//                $packageLog = new PackageLog();
//                $packageLog->package_id = $model->id;
//                $packageLog->created_at = $current_date;
//                $packageLog->user_id = $userId;
//                $packageLog->log = "【{$model->title}】更新，更新记录id【{$packageUpdateLog->id}】";
//                $re = $packageLog->save();
//                if (!$re) {
//                    throw new Exception('资产包日志保存失败');
//                }

                $transaction->commit();
                return array('state' => true, 'msg' => '保存成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                return array('state' => false, 'msg' => $e->getMessage());
            } catch (\Throwable $e) {
                $transaction->rollBack();
                return array('state' => false, 'msg' => $e->getMessage());
            }
        }
    }

    /**
     * 查看资产包
     *
     * @$id
     * @param $userId
     */
    public function selectPackage($model, $userId)
    {
        $packageLog = new PackageLog();
        $packageLog->package_id = $model->id;
        $packageLog->created_at = date('Y-m-d H:i:s');
        $packageLog->user_id = $userId;
        $packageLog->log = "查看资产包【{$model->title}】";
        $re = $packageLog->save();
        if (!$re) {
            return array('state' => false, 'msg' => '资产包日志保存失败');
        }
        return array('state' => true, 'msg' => '资产包日志保存成功');
    }


    /**
     * 删除资产包 （资产包转让、尽调等暂未考虑）
     *
     * @param $id 资产包id
     * @param $userId  用户id
     * @return array
     */
    public function deletePackage($id, $userId)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model = Package::findOne($id);
            $re = $model->delete();
            if (!$re) {
                throw new Exception("资产包{$model->title}删除失败");
            }

            $packageLog = new PackageLog();
            $packageLog->package_id = $model->id;
            $packageLog->created_at = date('Y-m-d H:i:s');
            $packageLog->user_id = $userId;
            $packageLog->log = "删除资产包【{$model->title}】";
            $re = $packageLog->save();
            if (!$re) {
                throw new Exception("资产包日志保存失败");
            }

            $transaction->commit();
            return array('state' => true, 'msg' => '删除成功');
        } catch (\Exception $e) {
            $transaction->rollBack();
            return array('state' => false, 'msg' => $e->getMessage());
        } catch (\Throwable $e) {
            $transaction->rollBack();
            return array('state' => false, 'msg' => $e->getMessage());
        }
    }


    /**
     * 资产包权限配置
     *
     * @param $id 资产包id
     * @param $userId  用户id
     * @return array
     */
    public function setPermissionForPackage($access_users, $access, $id)
    {
        $model = Package::findOne($id);
        $model->id = $id;
        $model->access = $access . "";
        $model->access_users = implode(",", $access_users);
        //$re = $model->update();
        $re = $model->save();
        if ($re) {
            //'总裁办', '风控管理中心', '财务部', '技术部'
            $data = ['not in','department',['ceooffice', 'windControlManagementCenter', 'finance', 'technology']];
            $userModel = new UserModel();
            $list = $userModel->getDepartmentUsersList();
            $userList = $userModel->getList($data);
            $ids = ArrayHelper::getColumn($userList, 'id');

            $tmp_msg = "";
            foreach ($model->getErrors() as $value) {
                $tmp_msg .= $value[0];
            }
            if ($tmp_msg == "") {
//                $packageLog = new PackageLog();
//                $packageLog->package_id = $model->id;
//                $packageLog->created_at = date('Y-m-d H:i:s');
//                $packageLog->user_id = Yii::$app->user->id;
//                $packageLog->log = "访问权限变更";
//                $re = $packageLog->save();
//                if (!$re) {
//                    throw new Exception('资产包日志保存失败');
//                }

                $packageLog = new PackageUpdateLog();
                $module_title_array = $packageLog->getModuleArrayTitle();
                $packageLog->package_id = $model->id;
                $packageLog->created_at = date('Y-m-d H:i:s');
                $packageLog->user_id = Yii::$app->user->id;
                $packageLog->module = $module_title_array[PackageUpdateLog::MODULE_PERMISSION];
                $user_name = array();
                //过滤默认部门人员
                if (!empty($list)) {
                    foreach($access_users as $value){
                        if (in_array($value, $ids)) {
                            array_push($user_name, $list[(int)$value]['realname']);
                        }
                    }
                } else {
                    foreach($access_users as $value){
                        if (in_array($value, $ids)) {
                            array_push($user_name, User::findOne($value)->realname);
                        }
                    }
                }
                $packageLog->log = "权限更改为：".join('，', $user_name);
                $re = $packageLog->save();
                if (!$re) {
                    throw new Exception('资产包日志保存失败');
                }
                return array('state' => true, 'msg' => '权限更新成功');
            } else {
                return array('state' => false, 'msg' => $tmp_msg);
            }
        }
        return array('state' => true, 'msg' => '权限更新成功');
    }

    /*获取尽调人员及头像显示（ly）*/
    public function getAvatar($state, $owner, $package_id)
    {
        $userID = Yii::$app->user->id;
        $data['editFlag'] = FALSE;
        if ($state > 1) {//说明已经发起协同
            $diligence = PackageInitiation::find()->select(['zongjian','leader', 'pre_evaluation', 'due_diligence'])->where(['package_id' => $package_id])->asArray()->one();
            $leader = trim($diligence['leader'], ',');
            $leader = explode(',', $leader);
            $pre_evaluation = trim($diligence['pre_evaluation'], ',');
            $pre_evaluation = explode(',', $pre_evaluation);
            $due_diligence = trim($diligence['due_diligence'], ',');
            $due_diligence = explode(',', $due_diligence);
            $data['zongjian'] = UserModel::find()->with('authItem')->select(['id', 'realname','department','avatar'])->where(['id'=>$diligence['zongjian']])->asArray()->one();
            $data['leader'] = UserModel::find()->with('authItem')->select(['id', 'realname','department','avatar'])->where(['in', 'id', $leader])->asArray()->all();
            $data['due_diligence'] = UserModel::find()->with('authItem')->select(['id', 'realname','department','avatar'])->where(['in', 'id', $due_diligence])->asArray()->all();
            $data['pre_evaluation'] = UserModel::find()->with('authItem')->select(['id', 'realname','department', 'avatar'])->where(['in', 'id', $pre_evaluation])->asArray()->all();
            if (strpos($diligence['zongjian'].$diligence['leader'] . $diligence['due_diligence'] . $diligence['pre_evaluation'], ',' . $userID . ',') == TRUE) $data['editFlag'] = TRUE;
        } else {//只显示上传人
            $res = UserModel::find()->with('authItem')->select(['id', 'realname','department', 'avatar'])->where(['id' => $owner])->asArray()->one();
            $data['owner'] = $res;
            if ($userID == $owner)//$editFlag
                $data['editFlag'] = TRUE;
        }
        return $data;
    }

    /**
     * 修改资产包日志
     * @param $id ID
     * @param $changedAttributes //保存数据
     * @param $userId 用户ID
     */
    public function setUpdateLog($id, $changedAttributes, $userId, $module)
    {
        $model = self::findOne((int)$id);
        if ($model === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        //判断数据是否发生改变
        $state = false;
        $data = array(); //修改后的数据
        foreach ($changedAttributes as $key => $value) {
            if ($model->$key != $value) {
                $data[$key] = $value;
                $state = true;
            }
        }

        if (!$state) {
            $model->lock_user = null;
            $model->lock_timestamp = null;
            if ($model->save()) {
                return array('state' => true, 'msg' => '保存成功');
            } else {
                return array('state' => false, 'msg' => '保存失败');
            }
            //return array('state' => false, 'msg' => '没有做任何修改');
        }

        //添加项目修改操作日志
        $users = new UserModel();
        $realname = $users->getRealname($userId);
        $userList = $users->getDepartmentUsersList();
        //省市
        $country_title = Country::getTitleList();
        //模型属性
        $attributeLabels = self::attributeLabels();
        $intAttributeLabels = ['category', 'type', 'access', 'access_users', 'province', 'city', 'principal_range', 'state', 'owner', 'teamwork', 'lock_user'];

        if (!empty($data)) {
            $log = '';
            foreach ($data as $key => $value) {
                if (in_array($key, $intAttributeLabels)) {
                    switch ($key) {
                        case 'category':
                            $title = $this->getCategoryArrayTitle();//Yii::$app->params['packageCategory'];
                            $value = $title[$value];
                            break;
                        case 'type':
                            $title = Yii::$app->params['package_type'];
                            $value = $title[$value];
                            break;
                        case 'access':
                            if (is_numeric($value)) {
                                $title = Yii::$app->params['access'];
                                $value = $title[$value];
                            }
                            break;
                        case 'access_users':
                            $arr = explode(',', trim($value, ','));
                            $str = '';
                            foreach ($arr as $v) {
                                $str .= $userList[(int)$v]['realname'] .'，';
                            }
                            $value = mb_substr($str, 0, -1, 'utf-8');
                            break;
                        case 'province':
                            $value = $country_title[$value];
                            break;
                        case 'city':
                            if ($value != '') {
                                $arr = explode(',', $value);
                                $array = array();
                                foreach ($arr as $k=>$v) {
                                    if ($v > 0){
                                        $array[] = $country_title[(int)$v];
                                    }
                                }
                                $value = join('、', $array);
                            } else {
                                $value = '';
                            }
                            break;
                        case 'principal_range':
                            $title = Yii::$app->params['principalRange'];
                            $value = $title[$value];
                            break;
                        case 'state':
                            $title = $this->getStateTitle();
                            $value = $title[$value];
                            break;
                        case 'owner':
                            $value = $users->getRealname($value);
                            break;
                        case 'teamwork':
                            $title = $this->getTeamworkTitle();
                            $value = $title[$value];
                            break;
                        case 'lock_user':
                            $value = $realname;
                            break;
                        default:
                    }
                }
                $log .= "{$attributeLabels[$key]}：{$value}\n";
            }

            try {
                $time = date('Y-m-d H:i:s');
                $packageUpdateLog = new PackageUpdateLog();
                $module_title_array = $packageUpdateLog->getModuleArrayTitle();
                $packageUpdateLog->package_id = $id;
                $packageUpdateLog->module = $module_title_array[$module];
                $packageUpdateLog->created_at = $time;
                $packageUpdateLog->user_id = $userId;
                $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');
                $re1 = $packageUpdateLog->save();
                if (!$re1) {
                    throw new Exception('资产包记录日志失败');
                }

//                $packageLog = new PackageLog();
//                $packageLog->package_id = $id;
//                $packageLog->created_at = $time;
//                $packageLog->user_id = $userId;
//                $packageLog->log = "【{$model->title}】更新，更新记录id【{$packageUpdateLog->id}】";
//                $re2  = $packageLog->save();
//                if (!$re2) {
//                    throw new Exception('资产包记录日志失败');
//                }
                return array('state' => true, 'msg' => '添加资产包操作日志成功');
            } catch (\Exception $e) {
                $message = $e->getMessage();
                return array('state' => false, 'msg' => $message);
            } catch (\Throwable $e) {
                $message = $e->getMessage();
                return array('state' => false, 'msg' => $message);
            }
        }
    }

}
